package com.javasee.common.dbsharding;

import com.javasee.common.dbsharding.router.SingleRouter;

public class DbShardingContextHolder {

    private static final ThreadLocal<DbshardingContext> contextHolder = new ThreadLocal<>();

    /**
     * 根据表名和分片参数，设置数据库 并返分表序号
     *
     * @param tbName
     * @param shardingParam
     * @return
     */
    public static Integer sharding(String tbName, String shardingParam) {
        DbShardingRouter router = DbShardingRouterFactory.getRouter(tbName);
        DbshardingContext context = new DbshardingContext();
        context.setDbIndex(router.getDbIndex(shardingParam));
        context.setTbIndex(router.getTbIndex(shardingParam));
        context.setTbName(tbName);
        context.setRealTbName(router.getRealTbName(tbName, context.getTbIndex()));
        contextHolder.set(context);
        return context.getTbIndex();
    }

    //单库单表
    public static Integer single(String tbName) {
        DbShardingRouter router = DbShardingRouterFactory.getRouter(tbName);
        if (router instanceof SingleRouter) {
            System.out.println("router = 单库单表");
        }
        DbshardingContext context = new DbshardingContext();
        context.setDbIndex(0);
        context.setTbIndex(0);
        context.setTbName(tbName);
        context.setRealTbName(tbName);
        contextHolder.set(context);
        return context.getTbIndex();
    }

    //指定库、表
    public static Integer assign(String tbName,int dbIndex,int tbIndex) {
        DbShardingRouter router = DbShardingRouterFactory.getRouter(tbName);
        if (router instanceof SingleRouter) {
            System.out.println("router = 单库单表,     指定库、表");
        }
        DbshardingContext context = new DbshardingContext();
        context.setDbIndex(dbIndex);
        context.setTbIndex(tbIndex); //0
        context.setTbName(tbName);
        context.setRealTbName(tbName);
        contextHolder.set(context);
        return context.getTbIndex();
    }

    public static Integer set(String tbName, Integer dbIndex, Integer tbIndex) {
        DbShardingRouter router = DbShardingRouterFactory.getRouter(tbName);
        DbshardingContext context = new DbshardingContext();
        context.setDbIndex(dbIndex);
        context.setTbIndex(tbIndex);
        context.setTbName(tbName);
        context.setRealTbName(router.getRealTbName(tbName, tbIndex));
        contextHolder.set(context);
        return context.getTbIndex();
    }

    public static DbshardingContext get() {
        return contextHolder.get();
    }


}